﻿#include "inbound.h"
#include "ui_inbound.h"

#include <QDateTime>

Inbound::Inbound(QDialog *parent, QString select_id_tmp) :
    QDialog(parent),
    ui(new Ui::Inbound),
    select_id(select_id_tmp)
{
    ui->setupUi(this);

    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    setFixedSize(this->width(),this->height());
    comboboxinit();//读取数据库商品编号到combo box

}

Inbound::~Inbound()
{
    delete ui;
}

void Inbound::on_inputButton_clicked()
{
    // 获取combo box控件里的值
    QString id = ui->idcomboBox->currentText();

    // 判断入库商品数量是否为空
    if(ui->amountlineEdit->text().isEmpty())
    {
        QMessageBox::information(this, "提示", "商品入库数量不能为空，请重试");
        ui->amountlineEdit->setFocus();
        return;
    }

    // 验证入库数量是否有效
    bool ok;
    int inputamount = ui->amountlineEdit->text().toInt(&ok);
    if (!ok || inputamount <= 0) {
        QMessageBox::information(this, "提示", "请输入有效的入库数量（必须为正整数）");
        ui->amountlineEdit->setFocus();
        ui->amountlineEdit->selectAll();
        return;
    }

    // 获取操作人
    QString operatorName = "系统管理员"; // 默认值
    // 如果有操作人输入框：QString operatorName = ui->operatorLineEdit->text();

    // 获取备注
    ///QString remarks = ui->remarksTextEdit->toPlainText(); // 如果有备注输入框
    QString remarks="";

    QSqlQuery sqlquery;
    QString strid = "StockId='";
    strid += id;
    strid += "'";

    QString str = QString("SELECT * FROM commoditydatatable WHERE %1").arg(strid);
    sqlquery.exec(str);

    QString strAmount;
    QString stockName;
    QString currentWarehouseTime; // 当前入库时间

    while(sqlquery.next())
    {
        strAmount = sqlquery.value(2).toString(); // 库存数量
        stockName = sqlquery.value(1).toString();  // 商品名称
        currentWarehouseTime = sqlquery.value(6).toString(); // 入库时间
    }

    int tableamount = strAmount.toInt();
    int isum = inputamount + tableamount;
    QString strisum = QString::number(isum);

    // 获取当前时间作为新的入库时间
    QString currentTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

    // 开始事务
    QSqlDatabase::database().transaction();

    // 更新数据表中数量字段和入库时间
    QString strdb;
    if (currentWarehouseTime.isEmpty()) {
        // 如果原来没有入库时间，设置当前时间为入库时间
        strdb = QString("UPDATE commoditydatatable SET StockAmount=%1, WareHousetime='%2' WHERE %3")
                    .arg(strisum, currentTime, strid);
    } else {
        // 如果原来有入库时间，更新为当前时间（最近入库时间）
        strdb = QString("UPDATE commoditydatatable SET StockAmount=%1, WareHousetime='%2' WHERE %3")
                    .arg(strisum, currentTime, strid);
    }

    if(sqlquery.exec(strdb))
    {
        // 添加库存操作记录（类型为"入库"）
        if(addStockOperationRecord("入库", id, stockName, inputamount, operatorName, remarks))
        {
            // 提交事务
            QSqlDatabase::database().commit();
            QMessageBox::information(this, "提示",
                                     QString("入库成功！\n\n"
                                             "商品：%1\n"
                                             "入库数量：%2\n"
                                             "当前库存：%3\n"
                                             "入库时间：%4")
                                         .arg(stockName)
                                         .arg(inputamount)
                                         .arg(isum)
                                         .arg(currentTime));

            // 清空输入框
            ui->amountlineEdit->clear();
            //ui->remarksTextEdit->clear(); // 如果有备注输入框

            accept(); // 关闭对话框
        }
        else
        {
            // 回滚事务
            QSqlDatabase::database().rollback();
            QMessageBox::information(this, "提示", "入库记录添加失败，操作已回滚");
        }
    }
    else
    {
        // 回滚事务
        QSqlDatabase::database().rollback();
        QMessageBox::information(this, "提示",
                                 QString("入库失败！错误信息：%1").arg(sqlquery.lastError().text()));
    }
}

void Inbound::on_exitButton_clicked()
{
    close();
}

//初始化combo box
void Inbound::comboboxinit()
{
    int i=0;
    QSqlQuery sqlQuery;
    sqlQuery.exec("select *from commoditydatatable");

    QString id;
    while(sqlQuery.next())
    {
        id=sqlQuery.value(0).toString();
        ui->idcomboBox->insertItem(i,id);
        i++;
    }
    ui->idcomboBox->setCurrentText(select_id);
}

// 添加库存操作记录
bool Inbound::addStockOperationRecord(const QString &operationType, const QString &stockId,
                                      const QString &stockName, int amount, const QString &operatorName,
                                      const QString &remarks)
{
    QSqlQuery query;

    // 准备SQL语句
    query.prepare("INSERT INTO stock_operations (operation_type, stock_id, stock_name, operation_amount, operator, operation_time, remarks) "
                  "VALUES (:operationType, :stockId, :stockName, :amount, :operator, :operationTime, :remarks)");

    // 绑定参数
    query.bindValue(":operationType", operationType);
    query.bindValue(":stockId", stockId);
    query.bindValue(":stockName", stockName);
    query.bindValue(":amount", amount);
    query.bindValue(":operator", operatorName);
    query.bindValue(":operationTime", QDateTime::currentDateTime());
    query.bindValue(":remarks", remarks);

    // 执行插入
    if(query.exec())
    {
        return true;
    }
    else
    {
        QMessageBox::warning(this, "警告",
                             QString("添加库存操作记录失败！错误信息：%1").arg(query.lastError().text()));
        return false;
    }
}
